<?php

/**
 * Linkshare iTunes App Store Link Handler
 *
 */
class Rsj_Linkshare
{
    protected $default_token_us = '03e58622d893c53003e95b991530251a245e9fe89365ec49929708f7ee3d3291';
    protected $default_token_jp = '24040617ce05bbb43ecfd482c9a2401732ae0712f2a0ea8bf30b2c8fcdc4c950';
    protected $affiliateUrl = null;
    protected static $cacheExpire = 86400; // = 60*60*24;
    protected static $merchantIdList = array(
        'us' => 13508, // Linkshare US
        'ca' => 25056, // Linkshare Canada
        'mx' => 37268, // Linkshare Mexico
        'jp' => 13894, // Linkshare Japan
    );

    protected $userAgent = null;
    const USER_AGENT_BASE = 'WordPress';
    public function __construct()
    {
        global $wp_version;
        $this->userAgent = self::USER_AGENT_BASE . '/' . $wp_version;
    }

    /**
     * get Linkshare affiliate token from WordPress options
     */
    public function getWebServiceToken( $country = 'us' )
    {
        switch ($country) {
            case 'jp':
                $token = $this->default_token_jp;
                $tokenKey = 'jp';
                break;
            case 'us':
            case 'ca':
            case 'mx':
            default:
                $token = $this->default_token_us;
                $tokenKey = 'us';
        }

        $options = get_option( Rsj_EmbedIphoneIpadApp::DB_OPTION_KEY );

        if ($options !== false
            && array_key_exists('affiliate', $options)
            && array_key_exists($tokenKey, $options['affiliate'])) {
          return $options['affiliate'][$tokenKey];
        }
        return $token;
    }

    /**
     * generate affiliate URL from (normalized) iTunes Store URL
     *
     * @originalUrl iTunes App Store URL (should be normalized)
     * @country country code to get affiliate URL
     * @return false if failed to fetch the info
     */
    public function getAffiliateUrl( $originalUrl, $country )
    {
        // cache during single response as this could be called multiple times
        if ( !is_null( $this->affiliateUrl ) ) {
            return $this->affiliateUrl;
        }

        $country = strtolower( $country );
        if ( array_key_exists( $country, self::$merchantIdList ) ) {
            $mid = self::$merchantIdList[$country];
        } else {
            $mid = self::$merchantIdList['us'];
        }

        $params = array(
            'tag' => 'wp-link-gen-c1',
            'token' => $this->getWebServiceToken( $country ),
            'mid' => $mid,
            'murl' => $originalUrl,
        );
        $response = wp_remote_request(
                'http://getdeeplink.linksynergy.com/createcustomlink.shtml?'
                . http_build_query( $params ), array(
            'user-agent' => $this->userAgent,
            'timeout' => 15,
                )
        );
        if ( is_wp_error( $response ) ) {
            throw new Rsj_EmbedIphoneIpadAppException(
                    __( 'Could not get an affiliate link' ), 503
            );
        }

        if ( !array_key_exists( 'body', $response ) ) {
            throw new Rsj_EmbedIphoneIpadAppException(
                    __( 'No affiliate link generated(no body)' ), 500
            );
        }
        $this->affiliateUrl = $response['body'];
        if ($response['body']
         === 'Automated LinkGenerator Web Service is not available for this Advertiser.') {
            throw new Rsj_EmbedIphoneIpadAppException(
                    __( 'No affiliate link generated(invalid advertiser)' ), 500
            );
        }
        if ( empty( $this->affiliateUrl ) ) {
            throw new Rsj_EmbedIphoneIpadAppException(
                    __( 'No affiliate link generated(blank url)' ), 500
            );
        }

        // filter_var() has a bug with hyphen in hostname
        //   ealier than PHP 5.2.14 and 5.3.3,
        //  https://bugs.php.net/bug.php?id=51192
        // but this bug does not affect Linkshare API's hostname
        $filtered = filter_var( $this->affiliateUrl, FILTER_VALIDATE_URL );
        if (!$filtered) {
            throw new Rsj_EmbedIphoneIpadAppException(
                    $this->affiliateUrl, 403
            );
        }

        return $this->affiliateUrl;
    }

    /**
     * ask Linkshare what online sellers I (a person set the token) have contracted.
     *
     * @return false if failed to fetch the info
     */
    /*
      public function getMerchantId()
      {
      $params = array(
      'token' => $this->getWebServiceToken(),
      'tag' => 'wp-merch-search-c1'
      );

      $response = wp_remote_request(
      'http://findadvertisers.linksynergy.com/merchantsearch?'
      . http_build_query($params),
      array(
      'user-agent' => $this->userAgent,
      'timeout' => 15,
      )
      );
      if ( is_wp_error( $response ) ) {
      echo 'Something went wrong!';

      return false;
      } else {
      echo 'Response:<pre>';
      print_r( $response );
      echo '</pre>';
      }

      return $response;
      }
     */
}
